<?php

namespace app\api\controller;

use app\common\controller\Wxpay;
use app\common\controller\Wxpay2;
use app\common\model\Wechat;
use app\common\model\Help;
use library\Controller;
use phpcode\QrCode;
use think\Db;
use think\App;
use app\store\service\GoodsService;
use app\store\service\OrderService;

class Device extends Controller
{
    public $header;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $help = new Help();
        $this->header = $help->em_getallheaders();
    }

    //充值
    public function charge()
    {
        $wechat = new Wechat();
        $_W = $wechat->mini_config($this->header);

        $data['user_id'] = $_POST['user_id'];
        $data['amount'] = $_POST['money'];
        $member = Db::table("store_member")->where(["id" => $data['user_id']])->find();
        $data['before'] = $member['amount'];
        $data['after'] = $member['amount']+$data['amount'];
        $data['memo'] = '余额充值';
        $data['out_trade_no'] = date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        $data['create_at'] = date('Y-m-d H:i:s');
        $data['lx'] = 0;
        $data['insert_id'] = Db::table("store_member_amount_log")->insertGetId($data);

        $body = '微信支付';

        $appid = $_W['app_id'];
        $openid = $member['openid']; //oQKgL0ZKHwzAY-KhiyEEAsakW5Zg
        $mch_id = $_W['mchid'];
        $key = $_W['wxkey'];
        $out_trade_no = $data['out_trade_no'];
        $total_fee = $data['amount'];
        $root = sysconf('realm_name') . '/index.php/api/device/charge_notify';

        if (empty($total_fee)) //押金
        {
            $total_fee = floatval(99 * 100);
        } else {
            $total_fee = floatval($total_fee * 100);
        }

        //$total_fee = 1;
        $weixinpay = new Wxpay($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee, $root);
        $return = $weixinpay->pay();
        echo json_encode($return);
    }

    //微信回调
    public function charge_notify()
    {
        $xml = file_get_contents('php://input');
        $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        if ($arr) {
            if ($arr['result_code'] == 'SUCCESS') {
                $out_trade_no = trim($arr['out_trade_no']);

                Db::table('store_member_amount_log')->where(array('out_trade_no' => $out_trade_no))->update(['is_pay' => 1, 'pay_no' => $arr['transaction_id'], 'pay_time' => date('Y-m-d H:i:s')]);

                $find = Db::table('store_member_amount_log')->where(array('out_trade_no' => $out_trade_no))->find();

                Db::table("store_member")->where(array('id' => $find['user_id']))->update(['amount'=> $find['after'] ]);
            }
        }

        $return = array('return_code' => 'SUCCESS', 'return_msg' => 'OK');
        $xml = '<xml>';
        foreach ($return as $k => $v) {
            $xml .= '<' . $k . '><![CDATA[' . $v . ']]></' . $k . '>';
        }
        $xml .= '</xml>';

        echo $xml;
        exit;
    }

    //余额新增记录
    public function insert_amount_log($data){
        $d['user_id'] = $data['user_id'];
        $d['amount'] = $data['pay_amount'];
        $member = Db::table("store_member")->where(["id" => $data['user_id']])->find();
        $d['before'] = $member['amount'];
        $d['after'] = $member['amount']-$d['amount'];
        $d['amount'] = '-'.$d['amount'];
        $d['memo'] = '余额支付';
        $d['out_trade_no'] = $data['out_trade_no'];
        $d['create_at'] = date('Y-m-d H:i:s');
        $d['lx'] = 1;
        $d['is_pay'] = 1;

        Db::table("store_member_amount_log")->insertGetId($d);
    }

    //积分新增记录
    public function insert_score_log($data){
        $d['user_id'] = $data['user_id'];
        $d['score'] = $data['score']*10;
        $member = Db::table("store_member")->where(["id" => $data['user_id']])->find();
        $d['before'] = $member['score'];
        $d['after'] = $member['score']-$d['score'];
        $d['score'] = '-'.$d['score'];
        $d['memo'] = '积分支付';
        $d['out_trade_no'] = $data['out_trade_no'];
        $d['create_at'] = date('Y-m-d H:i:s');
        $d['lx'] = 1;
        Db::table("store_member_score_log")->insertGetId($d);
    }

    public function insert_score_log2($data){
        $d['user_id'] = $data['user_id'];
        $d['score'] = sprintf('%.2f',($data['total_price']-$data['score']));
        $member = Db::table("store_member")->where(["id" => $data['user_id']])->find();
        $d['before'] = $member['score'];
        $d['after'] = $member['score']+$d['score'];
        $d['memo'] = '订单支付赠积分';
        $d['out_trade_no'] = $data['out_trade_no'];
        $d['create_at'] = date('Y-m-d H:i:s');
        $d['lx'] = 2;
        Db::table("store_member_score_log")->insertGetId($d);
    }

    //去支付订单
    public function pay(){
        $insertGetId = $_POST['order_id'];
        $order = Db::table("store_order_pay")->where("id=$insertGetId")->find();
        $amount = $order['pay_amount'];
        $user_id = $_POST['user_id'];
        $member = Db::table("store_member")->where(["id" => $_POST['user_id']])->find();
        $score = $order['score'];
        $total_price = $order['total_price'];

//        if($member['amount']<200){
//            echo json_encode(['code'=>400,'msg'=>'您的余额不足200元，请先充值在进行下单。','data'=>0]);
//            exit;
//        }

        if($order['pay_amount']>$member['amount']){
            echo json_encode(['code'=>400,'msg'=>'余额不足','data'=>0]);
            exit;
        }
        if($order['score']>$member['score']){
            echo json_encode(['code'=>400,'msg'=>'积分不足','data'=>0]);
            exit;
        }

        if($order['pay_amount']>0){

                $this->insert_amount_log($order);
                Db::query("update store_member set amount=amount-$amount where id=$user_id");

                if($score>0){
                    $this->insert_score_log($order);
                    $new_score = $score*10;
                    Db::query("update store_member set score=score-$new_score where id=$user_id");
                }

                $this->insert_score_log2($order);
                $gift_score = sprintf('%.2f',($total_price-$order['score']))??0;
                Db::query("update store_member set score=score+$gift_score where id=$user_id");


                Db::table("store_order_pay")->where(['out_trade_no'=>$order['out_trade_no']])->update(['status'=>2,'is_pay'=>1,'pay_time'=>date('Y-m-d H:i:s')]);
                echo json_encode(['code'=>200,'msg'=>'支付成功','data'=>1]);

        }else{

            $this->insert_score_log($order);
            $new_score = $score*10;
            Db::query("update store_member set score=score-$new_score where id=$user_id");

            $this->insert_score_log2($order);
            $gift_score = sprintf('%.2f',($total_price-$order['score']));
            Db::query("update store_member set score=score+$gift_score where id=$user_id");

            Db::table("store_order_pay")->where(['out_trade_no'=>$order['out_trade_no']])->update(['status'=>2,'is_pay'=>1,'pay_time'=>date('Y-m-d H:i:s')]);

            echo json_encode(['code'=>200,'msg'=>'支付成功','data'=>1]);
        }

    }


    //支付订单
    public function Payorder(){
        $member = Db::table("store_member")->where(["id" => $_POST['user_id']])->find();
        $type = $_POST['type']??1;

//        if($member['amount']<200){
//            echo json_encode(['code'=>500,'msg'=>'您的余额不足200元，请先充值在进行下单。','data'=>0]);
//            exit;
//        }


        if($type==1){
            $ishave = Db::table("store_cart")->where("id","in",$_POST['ids'])->select();
            if(empty($ishave)){
                echo json_encode(['code'=>500,'msg'=>'请不要重复支付','data'=>0]);
                exit;
            }
            $data['user_id'] = $user_id = $_POST['user_id'];
            $data['out_trade_no'] = date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);;
            $data['create_at'] = date('Y-m-d H:i:s');
            $cart = Db::table("store_cart")->where("id","in",$_POST['ids'])->field("id,user_id,package_id,project_id,total_price")->select();
            $data['order_json'] = json_encode($cart);
            $data['total_price'] = $total_price = $_POST['total_price']??0;
            $data['pay_amount'] = $amount = $_POST['pay_amount']??0;
            $data['score'] = $score = $_POST['score']??0;

            $insertGetId = Db::table("store_order_pay")->insertGetId($data);
            foreach ($cart as $key=>&$val){
                $this->insert_report($val,$insertGetId);
            }
            Db::table("store_cart")->where("id", "in", $_POST['ids'])->delete();

        }else{
            $ishave = Db::table("store_cart2")->where("user_id","in",$_POST['user_id'])->select();
            if(empty($ishave)){
                echo json_encode(['code'=>500,'msg'=>'请不要重复支付','data'=>0]);
                exit;
            }
            $data['user_id'] = $user_id = $_POST['user_id'];
            $data['out_trade_no'] = date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);;
            $data['create_at'] = date('Y-m-d H:i:s');
            $cart = Db::table("store_cart2")->where("user_id","in",$_POST['user_id'])->field("id,user_id,package_id,project_id,total_price")->select();
            $data['order_json'] = json_encode($cart);
            $data['total_price'] = $total_price = $_POST['total_price']??0;
            $data['pay_amount'] = $amount = $_POST['pay_amount']??0;
            $data['score'] = $score = $_POST['score']??0;

            $insertGetId = Db::table("store_order_pay")->insertGetId($data);
            foreach ($cart as $key=>&$val){
                $this->insert_report($val,$insertGetId);
            }
            Db::table("store_cart2")->where("user_id", "in", $_POST['user_id'])->delete();
        }

        if($_POST['pay_amount']>0){
            if($member['amount']>=$_POST['pay_amount']){

                $this->insert_amount_log($data);
                Db::query("update store_member set amount=amount-$amount where id=$user_id");

                if($score>0){
                    $this->insert_score_log($data);
                    $new_score = $score*10;
                    Db::query("update store_member set score=score-$new_score where id=$user_id");
                }

                $this->insert_score_log2($data);
                $gift_score = sprintf('%.2f',($total_price-$data['score']));
                Db::query("update store_member set score=score+$gift_score where id=$user_id");


                Db::table("store_order_pay")->where(['out_trade_no'=>$data['out_trade_no']])->update(['status'=>2,'is_pay'=>1,'pay_time'=>date('Y-m-d H:i:s')]);
                echo json_encode(['code'=>200,'msg'=>'支付成功','data'=>1]);
            }else{
                echo json_encode(['code'=>400,'msg'=>'余额不足','data'=>0]);
            }
        }else{

            $this->insert_score_log($data);
            $new_score = $score*10;
            Db::query("update store_member set score=score-$new_score where id=$user_id");

            $this->insert_score_log2($data);
            $gift_score = sprintf('%.2f',($total_price-$data['score']));
            Db::query("update store_member set score=score+$gift_score where id=$user_id");

            Db::table("store_order_pay")->where(['out_trade_no'=>$data['out_trade_no']])->update(['status'=>2,'is_pay'=>1,'pay_time'=>date('Y-m-d H:i:s')]);

            echo json_encode(['code'=>200,'msg'=>'支付成功','data'=>1]);
        }
    }


    //插入检测报告表
    public function insert_report($data,$insert_id){
        $d['user_id'] = $data['user_id'];
        $d['order_id'] = $insert_id;
        $d['package_id'] = $data['package_id'];
        $d['project_id'] = $data['project_id'];
        $d['create_at'] = date('Y-m-d H:i:s');
        Db::table("store_order_report")->insertGetId($d);
    }


    public function automatic_report(){
        $list = Db::table("store_order_pay")->select();
        foreach ($list as $k =>&$v){
            $order_json = json_decode($v['order_json'],true);
            foreach ($order_json as $kk =>&$vv){
                $this->insert_report($vv,$v['id']);
            }
        }
    }

    public function report_find(){
        $report_image = Db::table("store_order_report")->where(['order_id'=>$_POST['order_id'],'package_id'=>$_POST['id'],'project_id'=>$_POST['proid']])->value('report_image');
        echo json_encode($report_image);
    }


    //我的提交订单列表
    public function getOrderList()
    {
        $type = $_POST['type']??0;

        $user_id = $_POST['user_id']??'';
        $member = Db::table("store_member")->where("id=$user_id")->find();

        $whe = "";

        $page = ($_POST['page'] - 1) * 10;
        $order = "order by id desc";


        if($user_id){
            $whe = "user_id=$user_id";
        }

        if ($type == 1) {
            $list = Db::query("select * from store_order_pay where $whe and status =1  and is_deleted=0 $order limit $page,10");
            $total = count(Db::query("select id from store_order_pay where  $whe and status =1 and is_deleted=0 "));
        }elseif ($type == 2) {
            $list = Db::query("select * from store_order_pay where $whe and status =2     and is_deleted=0  $order limit $page,10");
            $total = count(Db::query("select id from store_order_pay where  $whe and status =2  and is_deleted=0"));
        }elseif ($type == 3) {
            $list = Db::query("select * from store_order_pay where $whe and status =3   and is_deleted=0 $order limit $page,10");
            $total = count(Db::query("select id from store_order_pay where  $whe and status =3  and is_deleted=0"));
        }elseif ($type == 4) {
            $list = Db::query("select * from store_order_pay where $whe and status =0   and is_deleted=0 $order limit $page,10");
            $total = count(Db::query("select id from store_order_pay where  $whe and status =0  and is_deleted=0"));
        }else{
            $list = Db::query("select * from store_order_pay where $whe and status =0   and is_deleted=0 $order limit $page,10");
            $total = count(Db::query("select id from store_order_pay where  $whe and status =0  and is_deleted=0"));
        }

        foreach ($list as $k => &$v) {
            $v['order_json'] = json_decode($v['order_json'],true);
            $v['total_goods'] = 0;
            foreach ($v['order_json'] as $kk =>&$vv) {
                $vv['package'] = Db::table("store_package")->where(["id" => $vv['package_id']])->where(["status" => 1, 'is_deleted' => 0])->find();
                $vv['project'] = Db::table("store_goods_cate")->where("id", "in", $vv['project_id'])->select();
                if ($vv['package']) {
                    $v['total_goods'] += 1;
                }
            }
        }

        echo json_encode(array('list' => $list, 'num' => count($list),'total'=>$total,'member'=>$member));
    }



    //签收完成订单
    public function qianshou(){
        Db::table("store_order")->where(['id'=>$_POST['id']])->update(['status'=>5]);
        echo 1;
    }


    //取消订单
    public function cancel_order()
    {
        Db::table("store_order_pay")->where(['id'=>$_POST['id']])->update(['status'=>0,'cancel_state'=>1,'cancel_at'=>date('Y-m-d H:i:s')]);
        echo 1;
    }


}